<template>
  <el-dialog v-model="dialogVisible" width="600" :title="title" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
    <base-skeleton v-if="pageLoad.loadState === true" style="width: 100%; height: 100%; min-height: 420px; padding: 0 20px"></base-skeleton>
    <template v-else-if="pageLoad.loadState === false">
      <el-form ref="elFormRef" :model="formData" :rules="rules" scrollToError statusIcon>
        <el-form-item label="用户" labelWidth="10em" prop="userId">
          <el-select v-model="formData.userId" placeholder="请选择用户" clearable>
            <el-option v-for="i in userList" :key="i.userId" :label="i.realname" :value="i.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短剧" labelWidth="10em" prop="dramaIds">
          <el-select v-model="formData.dramaIds" multiple placeholder="请选择短剧" clearable>
            <el-option v-for="i in dramaList" :key="i.dramaId" :label="i.dramaTitle" :value="i.dramaId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否能看金额" labelWidth="10em" prop="dramaIds">
          <el-switch
            v-model="formData.seeMoney"
            class="mb-2"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            activeText="开"
            inactiveText="关"
            :activeValue="1"
            :inactiveValue="0"
          ></el-switch>
        </el-form-item>
        <el-form-item labelWidth="0em">
          <div style="width: 100%; padding-top: 20px">
            <el-button style="width: 100%" type="success" :loading="submitLoading" :disabled="submitLoading" :icon="IconPlus" @click="submit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <base-empty
      v-else
      style="height: 100%"
      :description="pageLoad.description || ''"
      :imageSize="240"
      :loadState="pageLoad.loadState"
      :pageLoadButton="[{ text: '重新加载', callBack: getBaseDataAxios }]"
    ></base-empty>
  </el-dialog>
</template>

<script setup lang="ts">
  import IconPlus from '~icons/ep/plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import {
    type DistributionDataControlDramaItem,
    type DistributionDataControlItem,
    getDistributionDataDramaList,
    setDistributionData,
    type setDistributionDataRequest,
  } from '@/api/ledger-management.ts';
  import { type AdminUser, getAdminUserListNotPageAxios } from '@/api/permission-management.ts';

  type $AddShowData = {
    type: 'add';
    /** 添加时的回调 */
    addCallBack: () => void;
  };
  type $EditShowData = {
    type: 'edit';
    /** 角色 */
    role: DistributionDataControlItem;
    /** 编辑时的回调 */
    editCallBack: () => void;
  };

  const action = ref<'add' | 'edit'>('add');
  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });
  let addCallBack: $AddShowData['addCallBack'] | undefined = undefined;
  let editCallBack: $EditShowData['editCallBack'] | undefined = undefined;
  const submitLoading = ref(false);
  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const title: Ref<string> = ref('新增');
  const formData = reactive<setDistributionDataRequest>({
    dramaIds: [],
    dramaTitles: [],
    userId: undefined,
    seeMoney: 1,
  });

  const dramaList = ref<DistributionDataControlDramaItem[]>([]);
  const userList = ref<AdminUser[]>([]);

  const rules = computed<FormRules>(() => {
    const _rules: FormRules = {
      dramaIds: [{ required: true, message: '请选择短剧', trigger: ['blur', 'change'] }],
      userId: [{ required: true, type: 'number', message: '请选择用户', trigger: ['blur', 'change'] }],
    };
    return _rules;
  });

  /**
   * 显示
   */
  function show(data: $AddShowData | $EditShowData) {
    formData.dramaIds = [];
    formData.dramaTitles = [];
    formData.userId = undefined;
    editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;
    addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
    action.value = data.type;
    title.value = data.type === 'edit' ? '编辑' : '新增';
    dialogVisible.value = true;
    // if (data.type === 'edit' && typeof data.role) {
    //   formData.dramaId = data.role.dramaId;
    //   formData.dramaTitle = data.role.dramaTitle;
    //   formData.userId = data.role.userId;
    //   formData.createBy = data.role.createBy;
    // }

    getBaseDataAxios();
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  /** 提交 */
  async function submit() {
    try {
      await elFormRef.value?.validate();
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
      return;
    }
    try {
      submitLoading.value = true;
      if (action.value === 'edit') {
        typeof editCallBack === 'function' && editCallBack();
      } else {
        formData.dramaTitles = formData.dramaIds?.map((item) => {
          return dramaList.value.find((foo) => foo.dramaId === item)?.dramaTitle || '';
        });
        await setDistributionData(formData);
        typeof addCallBack === 'function' && addCallBack();
      }
      ElToast.success('提交成功');
      submitLoading.value = false;
      hide();
    } catch (error) {
      submitLoading.value = false;
      ElToast.error(error.msg || '提交失败，-BD003');
    }
  }

  /** 基础数据 */
  async function getBaseDataAxios() {
    try {
      pageLoad.loadState = true;
      const { data } = await getDistributionDataDramaList();
      const { data: userData } = await getAdminUserListNotPageAxios();
      dramaList.value = data;
      userList.value = userData;
      pageLoad.loadState = false;
    } catch (error) {
      pageLoad.loadState = 'err';
      pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
    }
  }

  defineExpose({ show, hide });
</script>
